package com.nstar.base.util
{
	import com.nstar.base.event.RequestEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
	
	import mx.rpc.IResponder;

	/**
	 * 下载工具类
	 * 后台下载，不需要通过对话框来保存
	 */ 
	public class Downloader extends EventDispatcher implements IResponder
	{
		public static const LOAD_COMPLETE:String = "loadComplete";
		public static const GET_CONFIG_COMPLETE:String = "getConfigComplete";
		
		private var _url:String;
		private var _path:String;
		private var _fileName:String;
		private var _deleteBefore:Boolean;//下载之前是否删除本地现有文件
		private var loader:URLStream;
		
		private var xmlLoader:LoadXMLDelegate;
		private var logger:Logger = Logger.getInstance(this);
		
		public function Downloader()
		{
		}
		
		//解析URL中文件名称
		private function parseName(url:String):String{
			var result:String = "";
			var idx:int = url.lastIndexOf("/");
			if(idx!=-1){
				result = url.substr(idx+1);
			}else{
				trace("error url~");
			}
			return result;
		}
		
		//从url处下载文件，保存到path目录中，文件名称默认与原文件名称相同
		//path可以带有目录，目录不存在时会自动生成
		//如: new DownloadUtils("http://www.abc.com/themes/HelloKitty.swf","themes");
		public function download(url:String,path:String,deleteBefore:Boolean = false):void{
			trace("download url : "+url);
			this._url = url;
			this._path = path;
			this._fileName = parseName(_url);
			this._deleteBefore = deleteBefore;

			loader = new URLStream();
			loader.addEventListener(Event.OPEN,loadHandler);
			loader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS,loadHandler);
			loader.addEventListener(IOErrorEvent.IO_ERROR,loadHandler);
			loader.addEventListener(ProgressEvent.PROGRESS,loadHandler);
			loader.addEventListener(Event.COMPLETE,loadHandler);
			loader.load(new URLRequest(_url));
		}
		
		private function loadHandler(event:Event):void{
			switch(event.type){
				case Event.OPEN:
					break;
				case HTTPStatusEvent.HTTP_RESPONSE_STATUS:
					break;
				case ProgressEvent.PROGRESS:
					break;
				case Event.COMPLETE:
					logger.debug("download complete~");
					var bytes:ByteArray = new ByteArray();
					loader.readBytes(bytes);
					//保存文件到本地
					saveAs(_path,_fileName,bytes);
					//事件通知
					this.dispatchEvent(new RequestEvent(LOAD_COMPLETE,bytes));
					break;
				case IOErrorEvent.IO_ERROR:
					logger.debug("download error~"+IOErrorEvent(event).text);
					break;
			}
		}
		
		//写bytes到url指定的文件中去
		private function saveAs(path:String,fileName:String,bytes:ByteArray):void{
			if(path.lastIndexOf("/")==-1){
				path = path + "/";
			}
			var fs:FileStream = new FileStream();
			var f:File = new File(File.applicationDirectory.resolvePath(path+fileName).nativePath);
			if(_deleteBefore && f.exists){
				f.deleteFile();
				trace("deleted local file");
			}
			
			fs.open(f,FileMode.WRITE);
			fs.position = 0;
			fs.writeBytes(bytes);
			fs.close();
		}
		
		//检查指定的url配置文件中，配置文件列表
		public function getConfigFileList(url:String):void{
			if(!xmlLoader){
				xmlLoader = new LoadXMLDelegate(this,url,"object");
			}
			xmlLoader.load();
		}
		
		//加载配置文件完成
		public function result(data:Object):void{
			this.dispatchEvent(new RequestEvent(GET_CONFIG_COMPLETE,data.result));
		}
		
		public function fault(info:Object):void{
			trace("load config xml error~");
		}
		
		/* 
		//获取DownloadUtils的配置文件完成
		private function getConfigCompleteHandler(event:RequestEvent):void{
			var themes:ArrayCollection = event.request.styles.style as ArrayCollection;
			//检查有无新的样式文件
			var files:Array = new Array();
			for each(var theme:Object in themes){
				var fileName:String = Utils.getFileName(theme.url);
				//检查文件是否存在
				var themeFile:File = new File(File.applicationDirectory.resolvePath("themes/"+fileName).nativePath);
				//如果文件不存在，则下载文件
				if(themeFile.exists == false){
					files.push(fileName);
					
					trace(fileName+" does not exists,downloading now ...");
					var downloader:Downloader = new Downloader();
					downloader.download(theme.url,"themes");
				}
			}
			
			if(files.length == 0){
				trace("no theme to upate");
			}
		}		
		 */
	}
}